package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    // 菜品列表
    @GetMapping("/dish/page")
    public ResultInfo findByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            String name) {// 1.接收参数
        // 2.调用service查询
        Page<Dish> dishPage = dishService.findByPage(pageNum, pageSize, name);
        // 3.返回结果
        return ResultInfo.success(dishPage);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    // 新增菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        dishService.save(dish);
        // 清理缓存
        String dishKey = "dish_"+dish.getCategoryId();
        redisTemplate.delete(dishKey);
        return ResultInfo.success();
    }

    // 回显菜品
    @GetMapping("/dish/{dishId}")
    public ResultInfo findById(@PathVariable("dishId") Long dishId) {

        return ResultInfo.success(dishService.findById(dishId));
    }


    // 抽取删除公共方法
    private void clean(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

    // 修改菜品
    @PutMapping("/dish")
    public ResultInfo updateDish(@RequestBody Dish dish) {
        dishService.updateDish(dish);

        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }



    // 起售、停售
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        dishService.updateStatus(status, ids);
        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    // 菜品删除
    @DeleteMapping("/dish")
    public ResultInfo deleteDish(@RequestParam List<Long> ids) {
        dishService.deleteDish(ids);
        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    // 根据分类查询菜品列表
    @GetMapping("/dish/list")
    public ResultInfo findListBySetmeal(Long categoryId, String name) {// 1.接收参数
        // 2.调用service
        List<Dish> dishList = dishService.findListBySetmeal(categoryId, name);
        // 3.返回结果
        return ResultInfo.success(dishList);
    }
}
